package com.boot_reggie.controller;

import com.boot_reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;
//    原始文件名

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        System.out.println(file);
        String orginalFlilename = file.getOriginalFilename();
//        截取图片.jpg后缀包括点
        String suffix = orginalFlilename.substring(orginalFlilename.lastIndexOf("."));
        String fileName = UUID.randomUUID().toString() + suffix;
        System.out.println(fileName);
//        创建一个目录对象
        File dir = new File(basePath);
        if(!dir.mkdir()){
            dir.mkdirs();
        }
        try{
            file.transferTo(new File(basePath + fileName));
        }catch (Exception ex){

        }
        return Result.success(fileName);
    };

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response){
        
        try{
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            ServletOutputStream outputStream =  response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();

        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
